<?php
namespace Controller;

use Slim\Container;
use Slim\Http\Request;
use Slim\Http\Response;
use Intervention\Image\ImageManagerStatic as Image;

class MainApi extends Base
{

    public function __construct(Container $container)
    {
        parent::__construct($container);
        $user = $this->getUser();
        if (empty($user)) {
            header("HTTP/1.1 400 Bad Request");
            echo 'no user error';
            exit;
        } else {
            $this->assign['user'] = $user;
        }
    }

    public function getactivity(Request $req, Response $res)
    {
        if ($this->checkfrom->regex('number', $req->getParam('page')) === false) {
            return $res->withStatus(400)->write('data error');
            exit;
        } else {
            $page = empty((int)$req->getParam('page')) ? 1 : (int)$req->getParam('page');
            $data = $this->db->where(['is_delete' => 0])->order(['createtime' => 'desc'])->limit($page, (int)$this->page['pagesize'])->select('tcp_activity');
            if ($data) {
                foreach ($data as $key => $value) {
                    $where['act_id'] = array($value['id']);
                    $data[$key]['starttime'] = date('Y.m.d', $value['starttime']);
                    $data[$key]['endtime'] = date('Y.m.d', $value['endtime']);
                    $data[$key]['joinnum'] = $this->db->where($where)->count('tcp_user_activity');
                }
                return $res->withJson(['data' => $data], 200);
                exit;
            } else {
                return $res->withStatus(400)->write('no data!');
                exit;
            }

        }

    }

    public function getclothing(Request $req, Response $res)
    {
        if ($this->checkfrom->regex('number', $req->getParam('page')) === false) {
            return $res->withStatus(400)->write('data error');
            exit;
        } else {
            $page = empty((int)$req->getParam('page')) ? 1 : (int)$req->getParam('page');
            $data = $this->db->where(['is_delete' => 0])->order(['createtime' => 'desc'])->limit($page, (int)$this->page['pagesize'])->select('tcp_clothing');
            if ($data) {
                foreach ($data as $key => $value) {
                    $where['cid'] = array($value['id']);
                    $data[$key]['starttime'] = date('Y.m.d', $value['starttime']);
                    $data[$key]['endtime'] = date('Y.m.d', $value['endtime']);
                    $data[$key]['joinnum'] = $this->db->where($where)->count('tcp_user_clothing');
                }
                return $res->withJson(['data' => $data], 200);
                exit;
            } else {
                return $res->withStatus(400)->write('no data!');
                exit;
            }

        }

    }

    public function doactivity(Request $req, Response $res)
    {
        $validate = $this->guard->validateToken($req->getParam('tk_name'), $req->getParam('tk_value'));
        if ($validate) {
            $user = $this->assign['user'];
            $id = (int)$req->getParam('id');
            if ($this->checkfrom->regex('number', $id) === false) {
                return $res->withStatus(400)->write('data error');
                exit;
            } else {
                $where['uid'] = array((int)$user['uid']);
                $where['act_id'] = array($id);
                if (!empty($this->db->where($where)->count('tcp_user_activity'))) {
                    return $res->withStatus(400)->write('该活动你已报名!');
                    exit;
                } else {
                    $_data = [
                        'uid' => (int)$user['uid'],
                        'act_id' => $id,
                        'createtime' => time()
                    ];
                    $this->db->startTrans();
                    $activitywhere['id'] = array($id);
                    $countwhere['act_id'] = array($id);
                    $activity = $this->db->where($activitywhere)->find('tcp_activity');
                    $countactivity = $this->db->where($countwhere)->count('tcp_user_activity');
                    if ((int)$user['intergtal'] < (int)$activity['maxintegral']) {
                        return $res->withStatus(400)->write('积分不足!');
                        exit;
                    } elseif ((int)$countactivity >= (int)$activity['maxnum']) {
                        return $res->withStatus(400)->write('报名人数已满!');
                        exit;
                    } else {
                        $intergtal = (int)$activity['maxintegral'];
                        $sqlstr = sprintf('UPDATE  `tcp_user` SET intergtal=intergtal-%s,updatetime=%s where uid = %s ', $intergtal, time(), (int)$user['uid']);
                        $updateuser = $this->db->doSql($sqlstr);
                        if ($this->db->insert('tcp_user_activity', $_data) && $updateuser) {
                            $this->db->commit();
                            return $res->withStatus(200)->write('报名成功!');
                            exit;
                        } else {
                            $this->db->rollback();
                            return $res->withStatus(400)->write('报名失败!');
                            exit;
                        }
                    }


                }
            }

        }
    }

    public function doclothing(Request $req, Response $res)
    {
        $validate = $this->guard->validateToken($req->getParam('tk_name'), $req->getParam('tk_value'));
        if ($validate) {
            $user = $this->assign['user'];
            $id = (int)$req->getParam('id');
            $colorid = (int)$req->getParam('colorid');
            $sizeid = (int)$req->getParam('sizeid');
            if ($this->checkfrom->regex('number', $id) === false && $this->checkfrom->regex('number', $colorid) === false && $this->checkfrom->regex('number', $sizeid) === false) {
                return $res->withStatus(400)->write('data error');
                exit;
            } else {

                $_data = [
                    'uid' => (int)$user['uid'],
                    'cid' => $id,
                    'colorid' => $colorid,
                    'sizeid' => $sizeid,
                    'createtime' => time()
                ];
                $this->db->startTrans();
                $where['id'] = array($id);
                $countwhere['cid'] = array($id);
                $clothing = $this->db->where($where)->find('tcp_clothing');
                $countclothing = $this->db->where($countwhere)->count('tcp_user_clothing');

                if ((int)$user['intergtal'] < (int)$clothing['integral']) {
                    return $res->withStatus(400)->write('积分不足!');
                    exit;
                } elseif ((int)$countclothing >= (int)$clothing['num']) {
                    return $res->withStatus(400)->write('库存不足!');
                    exit;
                } else {
                    $intergtal = (int)$clothing['integral'];
                    $sqlstr = sprintf('UPDATE  `tcp_user` SET intergtal=intergtal-%s,updatetime=%s where uid = %s ', $intergtal, time(), (int)$user['uid']);
                    $updateuser = $this->db->doSql($sqlstr);
                    if ($this->db->insert('tcp_user_clothing', $_data) && $updateuser) {
                        $this->db->commit();
                        return $res->withStatus(200)->write('兑换成功!');
                        exit;
                    } else {
                        $this->db->rollback();
                        return $res->withStatus(400)->write('兑换失败!');
                        exit;
                    }
                }
            }

        }
    }

    public function downimg(Request $req, Response $res)
    {
        $validate = $this->guard->validateToken($req->getParam('tk_name'), $req->getParam('tk_value'));
        if ($validate) {
            $count = 0;
            $user = $this->assign['user'];
            $base64_image_content = $req->getParam('localData');
//            $this->logger->addInfo('info', $base64_image_content);
            $mediatype = $req->getParam('mediatype');
            if (is_array($base64_image_content)) {

                //匹配出图片的格式
                foreach ($base64_image_content as $key => $value) {
                    if (strstr($value, ",")) {
                        $result = explode(',', $value);
                        $base64img = $result[1];

                    } else {
                        $base64img = $value;
                    }
                    $filepath = $this->checkuploadfile();
                    $name = uniqid() . time() . ".jpg";
                    $new_file = $filepath['filepath'] . '/' . $name;
                    if (file_put_contents($new_file, base64_decode($base64img))) {
                        $movethumbfile = $filepath['thumbfilepath'] . '/' . $name;
                        $image = Image::make($new_file);
                        $width = $image->width(); // 返回图片的宽度
                        $height = $image->height(); // 返回图片的高度
                        $col = round($width / $height, 1);

                        // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.jpg
                        $image->resize(320, round(320 / $col))->save($movethumbfile);
                        $data = [
                            'uid' => $user['uid'],
                            'media' => $name,
                            'mediatype' => $mediatype,
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                        $insert = $this->db->insert('tcp_user_share', $data);
                        if (!empty($insert)) {
                            $count++;
                            continue;
                        } else {
                            $count = 0;
                            break;
                        }


                    } else {
                        $count = 0;
                        break;
                    }
                }
                if (empty($count)) {
                    return $res->withStatus(400)->write('提交失败');
                    exit;
                } else {
                    return $res->withStatus(200)->write('提交成功');
                    exit;
                }
            } else {
                return $res->withStatus(400)->write('提交失败');
                exit;
            }


        } else {
            return $res->withStatus(400)->write('guard error');
            exit;
        }
    }

    public function getsharelist(Request $req, Response $res)
    {
        $user = $this->assign['user'];
        $_where = ' uid = ' . (int)$user['uid'];
        if ($this->checkfrom->regex('number', $req->getParam('page')) === true) {
            $_page = (int)$req->getParam('page');

        } else {
            $_page = 1;
        }
        if ($req->getParam('state') >= 0) {
            $_where .= '  and state = ' . (int)$req->getParam('state');
        }

        $list = $this->db->where($_where)->limit($_page, (int)$this->page['pagesize'])->order(array('createtime' => 'desc'))->select('tcp_user_share');
        if ($list) {
            foreach ($list as $key => $value) {
                $list[$key]['createtime'] = date('Y.m.d', $value['createtime']);
            }
            return $res->withJson(['data' => $list, 'page' => $_page + 1], 200);
            exit;
        } else {

            return $res->withStatus(400)->write('no data!');
            exit;
        }


    }

    public function dosign(Request $req, Response $res)
    {
        $validate = $this->guard->validateToken($req->getParam('tk_name'), $req->getParam('tk_value'));
        if ($validate) {
            $user = $this->assign['user'];
            $day = date('d');
            if(empty($user['signday'])){
                $signday=$day;
            }else{

                if(!strpos($user['signday'],$day)){
                  $signday=$user['signday'].','.$day;
                }else{$signday=$user['signday'];
                }

            }

            $min = $this->redis->get('min');
            $max = $this->redis->get('max');
            $intergtal= rand($min,$max);
            $_data=[
                'uid'=>$user['uid'],
                'signtime'=>strtotime(date('Y-m-d'))

            ];
            $this->db->startTrans();
            $isluck=0;
            $date=$this->getDate();
            $flag=0;
            foreach ($date as $value){
                $_where['uid']=array($user['uid']);
                $_where['signtime']=array((int)$value);
                $count=$this->db->where($_where)->count('tcp_user_sign');
                if(!empty($count)){
                    $flag++;
                    continue;
                }else{
                    $flag=0;
                    break;
                }

            }
            if(!empty($flag)){
                $isluck=1;
            }

            $add=$this->db->insert('tcp_user_sign',$_data);
            $sqlstr = sprintf('UPDATE  `tcp_user` SET intergtal=intergtal+%s,issign=%s,isluck=isluck+%s,signday=%s,updatetime=%s where uid = %s ', $intergtal,1,$isluck,"'$signday'",time(), (int)$user['uid']);
            $updateuser = $this->db->doSql($sqlstr);
            if($updateuser&&$add){
                $this->db->commit();
                return $res->withStatus(200)->write('每日签到获取随机积分'.$intergtal.'分');
                exit;
            }else{
                $this->db->rollback();

                       //  return $res->withStatus(400)->write('签到失败');
                return $res->withStatus(400)->write($signday);
                exit;
            }



        } else {
            return $res->withStatus(400)->write('guard error');
            exit;
        }
    }

    public function doluck(Request $req, Response $res)
    {
        $validate = $this->guard->validateToken($req->getParam('tk_name'), $req->getParam('tk_value'));
        if ($validate) {

            $user = $this->assign['user'];
            if(empty($user['isluck'])){
                return $res->withStatus(400)->write('抽奖次数用完');
                exit;
            }else{
                if ($this->checkfrom->regex('number', $req->getParam('intergtal')) === false ) {
                    return $res->withStatus(400)->write('积分格式错误');
                    exit;
                }else{

                    $intergtal= (int)$req->getParam('intergtal');
                    $sqlstr = sprintf('UPDATE  `tcp_user` SET intergtal=intergtal+%s,isluck=isluck-%s,updatetime=%s where uid = %s ', $intergtal,1,time(), (int)$user['uid']);
                    $updateuser = $this->db->doSql($sqlstr);
                    if($updateuser){
                        return $res->withStatus(200)->write('success');
                        exit;
                    }else{
                        return $res->withStatus(400)->write('data error');
                        exit;
                    }
                }
            }

        } else {
            return $res->withStatus(400)->write('guard error');
            exit;
        }
    }
    public function deletechildren(Request $req, Response $res){
        $cid=$req->getParam('cid');
        if ($this->checkfrom->regex('number', $cid) === false) {
            return $res->withStatus(400)->write('data error');
            exit;
        }else{
            $where['cid']=array((int)$cid);
            if($this->db->where($where)->delete('tcp_user_children')){
                return $res->withStatus(200)->write('删除成功');
                exit;
            }else{
                return $res->withStatus(400)->write('删除失败');
                exit;
            }
        }
    }
    public function doreceive(Request $req, Response $res){
        $user=$this->assign['user'];
        $sqlstr = sprintf('UPDATE  `tcp_user` SET intergtal=intergtal+%s,ischange=1,updatetime=%s where uid = %s ', 1000,time(), (int)$user['uid']);
        $updateuser = $this->db->doSql($sqlstr);
        if($updateuser){
            return $res->withStatus(200)->write('兑换成功');
            exit;
        }else{
            return $res->withStatus(400)->write('兑换失败');
            exit;
        }
    }

}